package itsm.isperp.framework.log;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

/**
 * 日记的切入记录
 * 
 * @author lizx
 * @date 2013-3-3
 * @version V1.0
 * 
 */
@Aspect
@Service
public class LoggingAspect {

	public static final Logger logger = LoggerFactory
			.getLogger(LoggingAspect.class);

	@Pointcut("execution(* itsm.isperp.*.*Service.*(..)) || execution(* itsm.isperp..*Service.*(..))")
	public void serviceMethod() {
	}

	@Before("serviceMethod()")
	public void beforeLogging(JoinPoint thisJoinPoint) {
		// Class<? extends Object> clazz = thisJoinPoint.getTarget().getClass();
		String methodName = thisJoinPoint.getSignature().getName();
		Object[] arguments = thisJoinPoint.getArgs();

		StringBuffer argBuf = new StringBuffer();
		StringBuffer argValueBuf = new StringBuffer();
		int i = 0;
		for (Object argument : arguments) {
			if (null == argument)
				return;
			String argClassName = argument.getClass().getSimpleName();
			if (i > 0) {
				argBuf.append(", ");
			}
			argBuf.append(argClassName + " arg" + ++i);
			argValueBuf.append(".arg").append(i).append(" : ")
					.append(argument.toString()).append("\n");
			//argValueBuf.append(ReflectionToStringBuilder.toString(argument));

		}

		if (i == 0) {
			argValueBuf.append("No arguments\n");
		}

		StringBuffer messageBuf = new StringBuffer();
		messageBuf.append("before executing " + methodName + "("
				+ argBuf.toString() + ") method");
		messageBuf
				.append("\n-------------------------------------------------------------------------------\n");
		messageBuf.append(argValueBuf.toString());
		messageBuf
				.append("\n-------------------------------------------------------------------------------\n");

		if (logger.isDebugEnabled()) {
			logger.debug(messageBuf.toString());
		}
	}
}
